
package com.plian.system.service.pm.property.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.plian.Tools.*;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.dao.pm.property.PropertyBasicsDao;
import com.plian.system.dao.pm.propertyout.PropertyOutDao;
import com.plian.system.entity.pm.property.*;
import com.plian.system.mapper.pm.property.PropertyBasicsMapper;
import com.plian.system.mapper.pm.property.PropertyChangeMapper;
import com.plian.system.mapper.pm.property.PropertyMapper;
import com.plian.system.mapper.pm.property.PropertyRecordMapper;
import com.plian.system.model.page.Page;
import com.plian.system.properties.GzwProperties;
import com.plian.system.service.pm.property.IContributorBasicsService;
import com.plian.system.service.pm.property.IPartnerSituationBasicsService;
import com.plian.system.service.pm.property.IPropertyBasicsService;
import com.plian.system.vo.pm.property.PropertyBasicsVO;
import com.plian.system.vo.pm.property.SmallPropertyBasicsVO;
import com.plian.system.wrapper.pm.property.PropertyBasicsWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

import static com.plian.system.constant.pm.OrganizationFormConstant.*;

/**
 *  服务实现类
 *
 * @author jianglei
 * @since 2019-12-05
 */
@Slf4j
@Service
@AllArgsConstructor
public class PropertyBasicsServiceImpl extends ServiceImpl<PropertyBasicsMapper, PropertyBasics> implements IPropertyBasicsService {

    private PropertyBasicsDao propertyBasicsDao;

    private IContributorBasicsService contributorBasicsService;

    private IPartnerSituationBasicsService partnerSituationBasicsService;

    private PropertyBasicsWrapper propertyBasicsWrapper;

    private GzwProperties gzwProperties;

    private PropertyMapper propertyMapper;

    private PropertyChangeMapper propertyChangeMapper;

    private PropertyRecordMapper recordMapper;

    private PropertyOutDao propertyOutDao;

    private final static int OUT_STATUS = 4;

    private final static List<String> CON_STATE_OWNED = Arrays.asList("057001","057002","057003","057004");


    @Override
    public boolean updateStatus(List<String> ids, String status) {
        LambdaUpdateWrapper<PropertyBasics> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(PropertyBasics::getId, ids).set(PropertyBasics::getStatus,status);
        return update(updateWrapper);
    }

    @Override
    public void initPropertyCode() {
        try{
            PropertyBasics root =  getOne(new LambdaQueryWrapper<PropertyBasics>()
                    .eq(PropertyBasics::getParentId, "0"));
            List<PropertyBasics> newOrgList = new ArrayList<>();
            List<PropertyBasics> propertyBasicsList=list();
            List<String> basicPropertyIds=propertyBasicsList.stream().map(record->record.getId()).collect(Collectors.toList());
            init(newOrgList, root, "0", 2);
            root.setPropertyCode("0");
            root.setPropertyLevel(1);
            newOrgList.add(root);
            //List<String> propertyIds=newOrgList.stream().map(record->record.getId()).collect(Collectors.toList());
            //List<PropertyBasics> noNodeIdsPropertyList=propertyBasicsList.stream().filter(record->!propertyIds.contains(record.getId())).collect(Collectors.toList());
            //List<String> noNodeIdsList=noNodeIdsPropertyList.stream().map(record->record.getId()).collect(Collectors.toList());
            propertyBasicsDao.updatePropertyCodeByIds(basicPropertyIds);
            updateBatchById(newOrgList);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void changeNewPropertyCode(String id, String parentId) {
        List<PropertyBasics> propertyBasicsList = list(new LambdaQueryWrapper<PropertyBasics>()
                .eq(PropertyBasics::getParentId, parentId).ne(PropertyBasics::getId, id));
        PropertyBasics propertyBasics = getById(id);
        PropertyBasics parentPropertyBasics = getById(parentId);
        if(null == propertyBasics || null == parentPropertyBasics) return;
        if (CollectionUtil.isEmpty(propertyBasicsList)){
            propertyBasics.setPropertyLevel(parentPropertyBasics.getPropertyLevel() + 1);
            propertyBasics.setPropertyCode(parentPropertyBasics.getPropertyCode() + StringPool.DOLLAR + "1");
        }

        int maxIndex = 1;
        for (PropertyBasics property : propertyBasicsList){
            String propertyCode = property.getPropertyCode();
            if (StringUtil.isBlank(propertyCode)){
                continue;
            }
            int index = Integer.valueOf(propertyCode.substring(propertyCode.lastIndexOf(StringPool.DOLLAR) + 1));
            if (index > maxIndex){
                maxIndex = index;
            }
        }
        propertyBasics.setPropertyLevel(parentPropertyBasics.getPropertyLevel() + 1);
        propertyBasics.setPropertyCode(parentPropertyBasics.getPropertyCode() + StringPool.DOLLAR + (maxIndex+1));
        List<PropertyBasics> newPropertyList = new ArrayList<>();
        init(newPropertyList, propertyBasics, propertyBasics.getPropertyCode(), propertyBasics.getPropertyLevel() + 1);
        updateById(propertyBasics);
        if (CollectionUtil.isNotEmpty(newPropertyList)){
            updateBatchById(newPropertyList);
        }
    }
    @Override
    public void changeNewPropertyCodeGzw(String id) {
        PropertyBasics propertyBasics = getById(id);
        if(null == propertyBasics) return;
        propertyBasics.setPropertyLevel(0);
        propertyBasics.setPropertyCode("0");
        updateById(propertyBasics);
    }
    @Override
    public void initIsPrivateMix() {
        List<PropertyBasics> allPropertyList = list();
        setIsPrivateMix(allPropertyList);
        updateBatchById(allPropertyList);
    }

    @Override
    public void changeChildPrivateMix(String initialId, Integer isPrivateMix) {
        PropertyBasics propertyBasics = getById(initialId);

        PropertyBasics parentProperty = null;
        String propertyCode = propertyBasics.getPropertyCode();
        if (propertyCode.contains(StringPool.DOLLAR)){
            String parentCode = propertyCode.substring(0, propertyCode.lastIndexOf(StringPool.DOLLAR));
            parentProperty = getOne(new LambdaQueryWrapper<PropertyBasics>()
                    .eq(PropertyBasics::getPropertyCode, parentCode));
        }
        if (parentProperty != null){
            if (parentProperty.getIsPrivateMix() != null && parentProperty.getIsPrivateMix() == 1){
                isPrivateMix = 1;
            }
        }
        propertyBasics.setIsPrivateMix(isPrivateMix);
        List<PropertyBasics> childList = list(new LambdaQueryWrapper<PropertyBasics>()
                .likeRight(PropertyBasics::getPropertyCode, propertyCode));
        List<PropertyBasics> updateList = new ArrayList<>();
        updateList.add(propertyBasics);
        if (CollectionUtil.isNotEmpty(childList)){
            for (PropertyBasics child : childList){
                if (isPrivateMix == 1){
                    child.setIsPrivateMix(1);
                }else {
                    setIsPrivateMix(childList);
                }
            }
            updateList.addAll(childList);
        }
        updateBatchById(updateList);
    }

    @Override
    public boolean checkActualCapital5(String actualCapital){
        if (Tools.isEmpty(actualCapital)) {
            actualCapital = "0";
        }
        double d = new BigDecimal(actualCapital).doubleValue();
        if (d > 0) {
            return true;
        } else {
            return false;
        }
    }
    @Override
    public List<SmallPropertyBasicsVO> getAllChildList() {
        String tokenOrgId = TokenUtil.getTokenOrgId();
        String competentOrganization = TokenUtil.getCompetentOrganization();
        PropertyBasics propertyBasics = getOne(new LambdaQueryWrapper<PropertyBasics>().eq(PropertyBasics::getOrgId, tokenOrgId)
                .eq(PropertyBasics::getStatus, 3)
                .eq(PropertyBasics::getCompetentOrganization, competentOrganization));
        if (propertyBasics == null){
            return null;
        }

        List<PropertyBasics> childList = list(new LambdaQueryWrapper<PropertyBasics>()
                .eq(PropertyBasics::getStatus, 3)
                .likeRight(PropertyBasics::getPropertyCode, propertyBasics.getPropertyCode()));
        List<String> propertyIdList = childList.stream().map(PropertyBasics::getId).collect(Collectors.toList());
        List<String> orgCodeList = childList.stream().map(PropertyBasics::getOrgCode).collect(Collectors.toList());
        List<ContributorBasics> contributorBasicsList = contributorBasicsService.list(new LambdaQueryWrapper<ContributorBasics>()
                .notIn(ContributorBasics::getPropertyId, propertyIdList).in(ContributorBasics::getOrgCode, orgCodeList));
        List<String> otherIds = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(contributorBasicsList)){
            otherIds.addAll(contributorBasicsList.stream().map(ContributorBasics::getPropertyId).collect(Collectors.toList()));
        }

        List<PartnerSituationBasics> partnerSituationBasicsList = partnerSituationBasicsService.list(new LambdaQueryWrapper<PartnerSituationBasics>()
                .notIn(PartnerSituationBasics::getPropertyId, propertyIdList).in(PartnerSituationBasics::getCode, orgCodeList));
        if (CollectionUtil.isNotEmpty(partnerSituationBasicsList)){
            otherIds.addAll(partnerSituationBasicsList.stream().map(PartnerSituationBasics::getPropertyId).collect(Collectors.toList()));
        }
        if (CollectionUtil.isNotEmpty(otherIds)){
            childList.addAll(list(new LambdaQueryWrapper<PropertyBasics>()
                    .eq(PropertyBasics::getStatus, 3)
                    .in(PropertyBasics::getId, otherIds).eq(PropertyBasics::getCompetentOrganization, competentOrganization)));
        }
        return propertyBasicsWrapper.entityToSmallVO(childList);
    }

    @Override
    public PropertyBasics findByOrgId(String orgId) {
        return getOne(new LambdaQueryWrapper<PropertyBasics>().eq(PropertyBasics::getOrgId, orgId));
    }

    @Override
    public List<PropertyBasics> getAllChild(String id) {
        if (StringUtil.isBlank(id)){
            return null;
        }
        PropertyBasics propertyBasics = getById(id);
        if (propertyBasics == null){
            return null;
        }
        return list(new LambdaQueryWrapper<PropertyBasics>().likeRight(PropertyBasics::getPropertyCode,propertyBasics.getPropertyCode()));
    }

    @Override
    public List<PropertyBasics> getAllChildByOrgIdsAndTime(List<String> orgIds, String bsDate) {
        List<PropertyBasics> allChildList = new ArrayList<>();
        List<PropertyBasics> propertyBasics = list(Wrappers.<PropertyBasics>lambdaQuery()
                .ne(PropertyBasics::getStatus, OUT_STATUS).in(CollectionUtil.isNotEmpty(orgIds),PropertyBasics::getOrgId, orgIds).le(StringUtil.isNotBlank(bsDate),PropertyBasics::getBsDate, bsDate).isNotNull(PropertyBasics::getPropertyCode));
        List<PropertyBasics> allProperBasics = list(Wrappers.<PropertyBasics>lambdaQuery().ne(PropertyBasics::getStatus, OUT_STATUS).isNotNull(PropertyBasics::getPropertyCode).eq(PropertyBasics::getCompetentOrganization, gzwProperties.getId()));
        if (CollectionUtil.isEmpty(propertyBasics)){
            return new ArrayList<>();
        }else {
            for (PropertyBasics basics:propertyBasics) {
                List<PropertyBasics> childList = allProperBasics.stream().filter(m -> m.getPropertyCode().contains(basics.getPropertyCode())).collect(Collectors.toList());
                allChildList.addAll(childList);
            }
        }

        return allChildList;
    }

    @Override
    public List<PropertyBasics> getMunicipalProperty(boolean flag,String date){
        List<PropertyBasics> list = new ArrayList<>();
        if (flag){
            list = list(Wrappers.<PropertyBasics>lambdaQuery().ne(PropertyBasics::getStatus, OUT_STATUS).le(StringUtil.isNotBlank(date),PropertyBasics::getBsDate, date)
                    .eq(PropertyBasics::getCompetentOrganization, gzwProperties.getId()));
        }else {
            list = list(Wrappers.<PropertyBasics>lambdaQuery().ne(PropertyBasics::getStatus, OUT_STATUS).le(StringUtil.isNotBlank(date),PropertyBasics::getBsDate, date)
                   );
        }
        return list;
    }
    @Override
    public PropertyBasicsVO findVOByOrgId(String orgId) {
        PropertyBasics propertyBasics = getOne(Wrappers.<PropertyBasics>lambdaQuery().eq(PropertyBasics::getOrgId, orgId));
        if (propertyBasics == null){
            return null;
        }
        return propertyBasicsWrapper.entityToVO(propertyBasics);
    }


    private void setIsPrivateMix(List<PropertyBasics> allPropertyList){
        List<PropertyBasics> specialPropertyList =  allPropertyList.stream()
                .filter(property -> StringUtil.isBlank(property.getPropertyCode()) || property.getPropertyLevel() == null)
                .collect(Collectors.toList());

        List<PropertyBasics> tempPropertyList = new ArrayList<>();
        List<String> privateMixPropertyCodeList = new ArrayList<>();
        List<String> privateMixIdList = new ArrayList<>();
        for (PropertyBasics property : allPropertyList){
            if (checkActualCapital5(property.getActualCapital5())) {
                property.setIsPrivateMix(1);
                if (StringUtil.isNotBlank(property.getPropertyCode())){
                    privateMixPropertyCodeList.add(property.getPropertyCode());
                }
                privateMixIdList.add(property.getId());
            } else {
                if (StringUtil.isNotBlank(property.getPropertyCode())){
                    tempPropertyList.add(property);
                }
                property.setIsPrivateMix(0);
            }
        }

        for (PropertyBasics property : tempPropertyList){
            String tempPropertyCode = property.getPropertyCode();
            while (tempPropertyCode.contains(StringPool.DOLLAR)){
                tempPropertyCode = tempPropertyCode.substring(0, tempPropertyCode.lastIndexOf(StringPool.DOLLAR));
                if (privateMixPropertyCodeList.contains(tempPropertyCode)){
                    property.setIsPrivateMix(1);
                    privateMixPropertyCodeList.add(property.getPropertyCode());
                    privateMixIdList.add(property.getId());
                    break;
                }
            }
        }

        for (PropertyBasics property : specialPropertyList){
            if (property.getIsPrivateMix() == 0
                    && StringUtil.isNotBlank(property.getParentId())
                    && privateMixIdList.contains(property.getParentId())){
                property.setIsPrivateMix(1);
            }
        }
    }

    private void init(List<PropertyBasics> newPropertyList, PropertyBasics propertyBasics, String parentCode, int level){
        List<PropertyBasics> childList = list(new LambdaQueryWrapper<PropertyBasics>()
                .eq(PropertyBasics::getParentId, propertyBasics.getId())
                .eq(PropertyBasics::getStatus, 3).orderByAsc(PropertyBasics::getUpdateTime));
        if (CollectionUtil.isEmpty(childList)){
            return;
        }

        for (int i = 0; i < childList.size(); i++){
            int index = i+1;
            String newCode = parentCode + StringPool.DOLLAR + index;
            PropertyBasics oldProperty = childList.get(i);
            oldProperty.setPropertyCode(newCode);
            oldProperty.setPropertyLevel(level);
            newPropertyList.add(oldProperty);
            init(newPropertyList, oldProperty, newCode, level + 1);
        }
    }

    @Override
    public Map<String, Object> decisionReport(String id,String startDate,String endDate){
        Map<String, Object> dataMap = new LinkedHashMap<>();
        dataMap.put("thisYear",endDate.split("-")[0]);
        dataMap.put("thisMonth",endDate.split("-")[0]);
        dataMap.put("lastYear",endDate.split("-")[0]);
        dataMap.put("lastMonth",endDate.split("-")[0]);
        PropertyBasics propertyBasics = getById(id);
        //获取当前时间产权下的出资人
        int childTotal = 0;
        List<PropertyBasics> childBasics = list(new LambdaQueryWrapper<PropertyBasics>()
                .ne(PropertyBasics::getId, id)
                .le(PropertyBasics::getUpdateTime,DateUtil.plusMonths(DateUtil.parse(endDate,DateUtil.PATTERN_MONTH),1))
                .likeRight(PropertyBasics::getPropertyCode, propertyBasics.getPropertyCode()));
        List<PropertyBasics> lastChildBasics = list(new LambdaQueryWrapper<PropertyBasics>()
                .ne(PropertyBasics::getId, id)
                .le(PropertyBasics::getUpdateTime,DateUtil.plusMonths(DateUtil.parse(startDate,DateUtil.PATTERN_MONTH),1))
                .likeRight(PropertyBasics::getPropertyCode, propertyBasics.getPropertyCode()));

        if (CollectionUtil.isNotEmpty(childBasics)){
            childTotal = childBasics.size();
        }
        List<ContributorBasics> contributorBasics = contributorBasicsService.list(new LambdaQueryWrapper<ContributorBasics>().eq(ContributorBasics::getPropertyId, id));
        if (CollectionUtil.isNotEmpty(contributorBasics)){
            childTotal = childTotal + contributorBasics.size();
            //出资企业及其各级子企业共计
            dataMap.put("childTotal" , childTotal);
            //实收资本总额
            BigDecimal contributionAmount = contributorBasics.stream().filter(con -> Optional.ofNullable(con.getContributionAmount()).isPresent())
                    .map(m -> new BigDecimal(m.getContributionAmount())).reduce(BigDecimal.ZERO, BigDecimal::add);
            dataMap.put("contributionAmount" , contributionAmount);
            //其中：占有国有资本
            BigDecimal stateContributionAmount = contributorBasics.stream().filter(con -> Optional.ofNullable(con.getContributionAmount()).isPresent())
                    .filter(con -> Optional.ofNullable(con.getCategory()).isPresent() && CON_STATE_OWNED.contains(con.getCategory()))
                    .map(m -> new BigDecimal(m.getContributionAmount())).reduce(BigDecimal.ZERO, BigDecimal::add);
            dataMap.put("stateContributionAmount" , stateContributionAmount);
            //国有资本占比
            if (contributionAmount.compareTo(BigDecimal.ZERO) > 0){
                dataMap.put("stateContributionRate" , stateContributionAmount.multiply(new BigDecimal(100)).divide(contributionAmount, 2, RoundingMode.HALF_UP));
            }else {
                dataMap.put("stateContributionRate" , BigDecimal.ZERO);
            }
            //其中外商
            BigDecimal otherContributionAmount = contributionAmount.subtract(stateContributionAmount);
            //外商资本占比
            if (otherContributionAmount.compareTo(BigDecimal.ZERO) > 0){
                dataMap.put("otherContributionRate" , otherContributionAmount.multiply(new BigDecimal(100)).divide(contributionAmount, 2, RoundingMode.HALF_UP));
            }else {
                dataMap.put("otherContributionRate" , BigDecimal.ZERO);
            }
        }
        //组织形式分布情况
        if (CollectionUtil.isNotEmpty(childBasics)){
            //公司制企业
            List<PropertyBasics> corporates = childBasics.stream().filter(m -> Optional.ofNullable(m.getOrganizationForm()).isPresent() && m.getOrganizationForm().contains(CORPORATE)).collect(Collectors.toList());
            int corporateTotal = 0;
            if (CollectionUtil.isNotEmpty(corporates)){
                corporateTotal = corporates.size();
                dataMap.put("corporateTotal" , corporateTotal);
                //占比
                dataMap.put("corporateRate" , new BigDecimal(corporateTotal * 100 ).divide(new BigDecimal(childTotal), 2, RoundingMode.HALF_UP));
                //有限责任公司
                List<PropertyBasics> limiteds = corporates.stream().filter(m -> Optional.ofNullable(m.getOrganizationForm()).isPresent() && LIMITED.equals(m.getOrganizationForm())).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(limiteds)){
                    int limitedTotal = limiteds.size();
                    dataMap.put("limitedTotal" , limitedTotal);
                    //占比
                    dataMap.put("limitedRate" , new BigDecimal(limitedTotal * 100 ).divide(new BigDecimal(childTotal), 2, RoundingMode.HALF_UP));
                }else {
                    dataMap.put("limitedTotal" , 0);
                    dataMap.put("limitedRate" , BigDecimal.ZERO);
                }
                //股份有限公司(非上市)
                List<PropertyBasics> shares = corporates.stream().filter(m -> Optional.ofNullable(m.getOrganizationForm()).isPresent() && SHARE.equals(m.getOrganizationForm())).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(shares)){
                    int shareTotal = shares.size();
                    dataMap.put("shareTotal" , shareTotal);
                    //占比
                    dataMap.put("shareRate" , new BigDecimal(shareTotal * 100 ).divide(new BigDecimal(childTotal), 2, RoundingMode.HALF_UP));
                }else {
                    dataMap.put("shareTotal" , 0);
                    dataMap.put("shareRate" , BigDecimal.ZERO);
                }
                //股份有限公司(上市)
                List<PropertyBasics> listedShares = corporates.stream().filter(m -> Optional.ofNullable(m.getOrganizationForm()).isPresent() && GO_PUBLIC.equals(m.getOrganizationForm())).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(listedShares)) {
                    int listedShareTotal = listedShares.size();
                    dataMap.put("listedShareTotal", listedShareTotal);
                    //占比
                    dataMap.put("listedShareRate", new BigDecimal(listedShareTotal * 100).divide(new BigDecimal(childTotal), 2, RoundingMode.HALF_UP));
                }else {
                    dataMap.put("listedShareTotal", 0);
                    dataMap.put("listedShareRate", BigDecimal.ZERO);
                }
            }
            //非公司制企业
            List<PropertyBasics> nonCorporates = childBasics.stream().filter(m -> Optional.ofNullable(m.getOrganizationForm()).isPresent() && m.getOrganizationForm().contains(NOCORPORATE)).collect(Collectors.toList());
            int noCorporateTotal = 0;
            if (CollectionUtil.isNotEmpty(nonCorporates)){
                noCorporateTotal = nonCorporates.size();
                dataMap.put("noCorporateTotal" , noCorporateTotal);
                //占比
                dataMap.put("noCorporateRate" , new BigDecimal(noCorporateTotal * 100 ).divide(new BigDecimal(childTotal), 2, RoundingMode.HALF_UP));
                //全民所有制
                List<PropertyBasics> allPeople = nonCorporates.stream().filter(m -> Optional.ofNullable(m.getOrganizationForm()).isPresent() && ALL_PEOPLE.equals(m.getOrganizationForm())).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(allPeople)) {
                    dataMap.put("allPeopleTotal", allPeople.size());
                }else {
                    dataMap.put("allPeopleTotal", 0);
                }
                //集体企业
                List<PropertyBasics> collective = nonCorporates.stream().filter(m -> Optional.ofNullable(m.getOrganizationForm()).isPresent() && COLLECTIVE.equals(m.getOrganizationForm())).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(collective)) {
                    dataMap.put("collectiveTotal", collective.size());
                }else {
                    dataMap.put("collectiveTotal", 0);
                }
                //联营企业
                List<PropertyBasics> jointVenture = nonCorporates.stream().filter(m -> Optional.ofNullable(m.getOrganizationForm()).isPresent() && JOINT.equals(m.getOrganizationForm())).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(jointVenture)) {
                    dataMap.put("jointVentureTotal", jointVenture.size());
                }else {
                    dataMap.put("jointVentureTotal", 0);
                }
            }

            //事业单位
            List<PropertyBasics> causes = childBasics.stream().filter(m -> Optional.ofNullable(m.getOrganizationForm()).isPresent() && CAUSE.equals(m.getOrganizationForm())).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(causes)){
                dataMap.put("causeTotal", causes.size());
            }else {
                dataMap.put("causeTotal", 0);
            }
            //有限合伙企业
            List<PropertyBasics> limitedPartnership = childBasics.stream().filter(m -> Optional.ofNullable(m.getOrganizationForm()).isPresent() && LIMITED_PARTNERSHIP.equals(m.getOrganizationForm())).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(limitedPartnership)){
                dataMap.put("limitedPartnershipTotal", limitedPartnership.size());
            }else {
                dataMap.put("limitedPartnershipTotal", 0);
            }
            //其他（民办非企业）
            List<PropertyBasics> noGovernments = childBasics.stream().filter(m -> Optional.ofNullable(m.getOrganizationForm()).isPresent() && NO_GOVERNMENT.equals(m.getOrganizationForm())).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(noGovernments)){
                dataMap.put("noGovernmentTotal", noGovernments.size());
            }else {
                dataMap.put("noGovernmentTotal", 0);
            }
            //对比
            if (CollectionUtil.isNotEmpty(lastChildBasics)){
                //公司制企业
                List<PropertyBasics> lastCorporates = lastChildBasics.stream().filter(m -> Optional.ofNullable(m.getOrganizationForm()).isPresent() && m.getOrganizationForm().contains(CORPORATE)).collect(Collectors.toList());
                int lastCorporateTotal = 0;
                if (CollectionUtil.isNotEmpty(lastCorporates)){
                    lastCorporateTotal = lastCorporates.size();
                }
                int corporateCompare = corporateTotal - lastCorporateTotal;
                if (corporateCompare > 0){
                    dataMap.put("corporateCompare" , "增加"+corporateCompare+"户");
                }else if (corporateCompare < 0) {
                    dataMap.put("corporateCompare", "减少" + Math.abs(corporateCompare) + "户");
                }else {
                    dataMap.put("corporateCompare", "无变化");
                }
                if (corporateTotal >0){
                    dataMap.put("corporateCompareRate", new BigDecimal(corporateCompare * 100).divide(new BigDecimal(corporateTotal), 2, RoundingMode.HALF_UP));
                }else {
                    dataMap.put("corporateCompareRate", "0");
                }
                //非公司制企业
                List<PropertyBasics> lastNonCorporates = lastChildBasics.stream().filter(m -> Optional.ofNullable(m.getOrganizationForm()).isPresent() && m.getOrganizationForm().contains(NOCORPORATE)).collect(Collectors.toList());
                int lastNonCorporateTotal = 0;
                if (CollectionUtil.isNotEmpty(lastNonCorporates)){
                    lastNonCorporateTotal = lastNonCorporates.size();
                }
                int noCorporateCompare = noCorporateTotal - lastNonCorporateTotal;
                if (noCorporateCompare > 0){
                    dataMap.put("noCorporateCompare" , "增加"+noCorporateCompare+"户");
                }else if (noCorporateCompare < 0) {
                    dataMap.put("noCorporateCompare", "减少" + Math.abs(noCorporateCompare) + "户");
                }else {
                    dataMap.put("noCorporateCompare", "无变化");
                }
                if (noCorporateTotal >0){
                    dataMap.put("noCorporateCompareRate", new BigDecimal(noCorporateCompare * 100).divide(new BigDecimal(noCorporateTotal), 2, RoundingMode.HALF_UP));
                }else {
                    dataMap.put("noCorporateCompareRate", "0");
                }
            }
        }
        //级次分布情况
        if (CollectionUtil.isNotEmpty(childBasics)){
            Map<String, List<PropertyBasics>> mapByOrgGradation = childBasics.stream().filter(m -> Optional.ofNullable(m.getOrgGradation()).isPresent()).collect(Collectors.groupingBy(PropertyBasics::getOrgGradation));
                        int firstTotal = 0;
            if (CollectionUtil.isNotEmpty(mapByOrgGradation.get("001001"))){
                firstTotal = mapByOrgGradation.get("001001").size();
            }
            dataMap.put("firstTotal" ,firstTotal);
            dataMap.put("firstRate" ,new BigDecimal(firstTotal * 100).divide(new BigDecimal(childBasics.size()), 2, RoundingMode.HALF_UP));
            int secondTotal = 0;
            if (CollectionUtil.isNotEmpty(mapByOrgGradation.get("001002"))){
                secondTotal = mapByOrgGradation.get("001002").size();
            }
            dataMap.put("secondTotal" ,secondTotal);
            dataMap.put("secondRate" ,new BigDecimal(secondTotal * 100).divide(new BigDecimal(childBasics.size()), 2, RoundingMode.HALF_UP));
            int thirdTotal = 0;
            if (CollectionUtil.isNotEmpty(mapByOrgGradation.get("001003"))){
                thirdTotal = mapByOrgGradation.get("001003").size();
            }
            dataMap.put("thirdTotal" ,thirdTotal);
            dataMap.put("thirdRate" ,new BigDecimal(thirdTotal * 100).divide(new BigDecimal(childBasics.size()), 2, RoundingMode.HALF_UP));
            int fourthTotal = childBasics.size() - firstTotal - secondTotal - thirdTotal;
            dataMap.put("fourthTotal" ,fourthTotal);
            dataMap.put("fourthRate" ,new BigDecimal(fourthTotal * 100).divide(new BigDecimal(childBasics.size()), 2, RoundingMode.HALF_UP));

            if (CollectionUtil.isNotEmpty(lastChildBasics)){
                Map<String, List<PropertyBasics>> lastByOrgGradation = lastChildBasics.stream().filter(m -> Optional.ofNullable(m.getOrgGradation()).isPresent()).collect(Collectors.groupingBy(PropertyBasics::getOrgGradation));
                int lastFirstTotal = 0;
                if (CollectionUtil.isNotEmpty(lastByOrgGradation.get("001001"))){
                    lastFirstTotal = lastByOrgGradation.get("001001").size();
                }
                int firstCompare = firstTotal - lastFirstTotal;
                if (firstCompare > 0){
                    dataMap.put("firstCompare" , "增加"+firstCompare+"户");
                }else if (firstCompare < 0) {
                    dataMap.put("firstCompare", "减少" + Math.abs(firstCompare) + "户");
                }else {
                    dataMap.put("firstCompare", "无变化");
                }
                if (firstTotal >0){
                    dataMap.put("firstCompareRate", new BigDecimal(firstCompare * 100).divide(new BigDecimal(firstTotal), 2, RoundingMode.HALF_UP));
                }else {
                    dataMap.put("firstCompareRate", "0");
                }
                int lastSecondTotal = 0;
                if (CollectionUtil.isNotEmpty(lastByOrgGradation.get("001002"))){
                    lastSecondTotal = lastByOrgGradation.get("001002").size();
                }
                int secondCompare = secondTotal - lastSecondTotal;
                if (secondCompare > 0){
                    dataMap.put("secondCompare" , "增加"+secondCompare+"户");
                }else if (secondCompare < 0) {
                    dataMap.put("secondCompare", "减少" + Math.abs(secondCompare) + "户");
                }else {
                    dataMap.put("secondCompare", "无变化");
                }
                if (secondTotal >0){
                    dataMap.put("secondCompareRate", new BigDecimal(secondCompare * 100).divide(new BigDecimal(secondTotal), 2, RoundingMode.HALF_UP));
                }else {
                    dataMap.put("secondCompareRate", "0");
                }

                int lastThirdTotal = 0;
                if (CollectionUtil.isNotEmpty(lastByOrgGradation.get("001003"))){
                    lastThirdTotal = lastByOrgGradation.get("001003").size();
                }
                int thirdCompare = thirdTotal - lastThirdTotal;
                if (thirdCompare > 0){
                    dataMap.put("thirdCompare" , "增加"+thirdCompare+"户");
                }else if (secondCompare < 0) {
                    dataMap.put("thirdCompare", "减少" + Math.abs(thirdCompare) + "户");
                }else {
                    dataMap.put("thirdCompare", "无变化");
                }
                if (thirdTotal >0){
                    dataMap.put("thirdCompareRate", new BigDecimal(thirdCompare * 100).divide(new BigDecimal(thirdTotal), 2, RoundingMode.HALF_UP));
                }else {
                    dataMap.put("thirdCompareRate", "0");
                }

                int lastFourthTotal = childBasics.size() - lastFirstTotal - lastSecondTotal - lastThirdTotal;
                int fourthCompare = fourthTotal - lastFourthTotal;
                if (fourthCompare > 0){
                    dataMap.put("fourthCompare" , "增加"+fourthCompare+"户");
                }else if (secondCompare < 0) {
                    dataMap.put("fourthCompare", "减少" + Math.abs(fourthCompare) + "户");
                }else {
                    dataMap.put("fourthCompare", "无变化");
                }
                if (fourthTotal >0){
                    dataMap.put("fourthCompareRate", new BigDecimal(fourthCompare * 100).divide(new BigDecimal(fourthTotal), 2, RoundingMode.HALF_UP));
                }else {
                    dataMap.put("fourthCompareRate", "0");
                }

            }

        }
        //区域分布情况
        if (CollectionUtil.isNotEmpty(childBasics)){
            //境内
            List<PropertyBasics> withinBasics = childBasics.stream().filter(m -> Optional.ofNullable(m.getNature()).isPresent() && "0".equals(m.getNature())).collect(Collectors.toList());
            int withinTotal = 0;
            BigDecimal withinAmount =BigDecimal.ZERO;
            if (CollectionUtil.isNotEmpty(withinBasics)){
                withinTotal = withinBasics.size();
                List<ContributorBasics> withinCon = contributorBasicsService.list(new LambdaQueryWrapper<ContributorBasics>().in(ContributorBasics::getCategory,CON_STATE_OWNED)
                        .in(ContributorBasics::getPropertyId, withinBasics.stream().map(PropertyBasics::getId).collect(Collectors.toList())));
                if (CollectionUtil.isNotEmpty(withinCon)){
                    withinAmount = withinCon.stream().map(m -> new BigDecimal(m.getContributionAmount())).reduce(BigDecimal.ZERO, BigDecimal::add);
                }
            }
            dataMap.put("withinTotal" ,withinTotal);
            dataMap.put("withinAmount" ,withinAmount);
            //境外
            List<PropertyBasics> withoutBasics = childBasics.stream().filter(m -> Optional.ofNullable(m.getNature()).isPresent() && "1".equals(m.getNature())).collect(Collectors.toList());
            int withoutTotal = 0;
            BigDecimal withoutAmount =BigDecimal.ZERO;
            if (CollectionUtil.isNotEmpty(withoutBasics)){
                withoutTotal = withoutBasics.size();
                List<ContributorBasics> withoutCon = contributorBasicsService.list(new LambdaQueryWrapper<ContributorBasics>().in(ContributorBasics::getCategory,CON_STATE_OWNED)
                        .in(ContributorBasics::getPropertyId, withoutBasics.stream().map(PropertyBasics::getId).collect(Collectors.toList())));
                if (CollectionUtil.isNotEmpty(withoutCon)){
                    withoutAmount = withoutCon.stream().map(m -> new BigDecimal(m.getContributionAmount())).reduce(BigDecimal.ZERO, BigDecimal::add);
                }
            }
            dataMap.put("withoutTotal" ,withoutTotal);
            dataMap.put("withoutAmount" ,withoutAmount);
        }
        //变动分析
        if (CollectionUtil.isNotEmpty(childBasics)){
            List<String> proIds = childBasics.stream().map(PropertyBasics::getId).collect(Collectors.toList());
            int propertySize = 0;
            List<Property> properties = propertyMapper.selectList(new LambdaQueryWrapper<Property>().in(Property::getId, proIds));
            if (CollectionUtil.isNotEmpty(properties)){
                propertySize  = properties.size();
            }
            dataMap.put("propertySize" ,propertySize);

            List<PropertyRecord> recordList = recordMapper.selectList(new LambdaQueryWrapper<PropertyRecord>().in(PropertyRecord::getPropertyId, proIds));
            if (CollectionUtil.isNotEmpty(recordList)) {
                List<String> recordIds = recordList.stream().map(PropertyRecord::getId).collect(Collectors.toList());
                //变动登记
                List<PropertyChange> propertyChanges = propertyChangeMapper.selectList(new LambdaQueryWrapper<PropertyChange>().in(PropertyChange::getProId, recordIds));
                int changeSize = 0;
                if (CollectionUtil.isNotEmpty(propertyChanges)){
                    changeSize = propertyChanges.size();
                }
                dataMap.put("changeSize" ,changeSize);
            }

            //注销登记
            PageData pageData=new PageData();
            Page page=new Page(false,pageData);
            try {
                List<PageData> propertyOuts = propertyOutDao.listPage(page);
                if (CollectionUtil.isNotEmpty(propertyOuts)){
                    dataMap.put("outSize" ,propertyOuts.size());
                }else {
                    dataMap.put("outSize" ,0);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return dataMap;
    }

    @Override
    public List<PropertyBasics> nameLikeList(String proName){
        return list(Wrappers.<PropertyBasics>lambdaQuery().like(PropertyBasics::getOrgName,proName).eq(PropertyBasics::getStatus, FormStatusConstant.FINISH));
    }
}
